package com.ilovepostcard;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.DrawableManager;

public class SearchResultUserActivtiy extends BaseActivity{

	
	ListView list;
	String key;
	TextView mResult;
	@Override
    public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_result_user);
		key = this.getIntent().getStringExtra("key");
		init();
	}
	
	private void filterSelf(ArrayList<User> userList) {
	    User self = UserController.getLoginUser(this);
	    for (Iterator<User> i = userList.iterator();i.hasNext();) {
	        User user = i.next();
	        if (user.UserID == self.UserID)
	            i.remove();
	    }
	}
	
	private void init()
	{
	    new ServerAsyncTask(this) {
            
            @Override
            protected void onSuccess(PostcardResult result) {
                final ArrayList<User> resList = result.getSearchUsers();
                list = (ListView)findViewById(R.id.search_result_list);
                mResult = (TextView)findViewById(R.id.search_result);
                String message = SearchResultUserActivtiy.this.getResources().getString(R.string.search_result_pc);
        		String formatMSG = String.format(message, resList.size());
        		mResult.setText(formatMSG);
                filterSelf(resList);
                SearchListAdapter adapter = new SearchListAdapter(resList);
                
                list.setAdapter(adapter);
                list.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        final Context context = SearchResultUserActivtiy.this;
                        final User user = resList.get(position);
                        new ServerAsyncTask(context) {
                            
                            @Override
                            protected void onSuccess(PostcardResult result) {
                                final User detailUser = result.getUser();
                                
                                new ServerAsyncTask(context) {
                                    
                                    @Override
                                    protected void onSuccess(PostcardResult result) {
                                        Intent intent = new Intent(context, UserActivity.class);
                                        intent.putExtra("user", detailUser);
                                        intent.putExtra("attention", result.getCheckAttention());
                                        context.startActivity(intent);
                                    }
                                    
                                    @Override
                                    protected PostcardResult doRequest() {
                                        return ServerFactory.getServer().checkAttention(UserController.getLoginUser(context).UserID, detailUser.UserID);
                                    }
                                    
                                }.execute();
                            }
                            
                            @Override
                            protected PostcardResult doRequest() {
                                return ServerFactory.getServer().getUserInfo("", user.UserID);
                            }
                        }.execute();
                    }
                    
                });
            }
            
            @Override
            protected PostcardResult doRequest() {
                return ServerFactory.getServer().searchUser(key, 1, 100);
            }
        }.execute();
	    
		
	}
	
	
	class SearchListAdapter extends BaseAdapter
	{

		ArrayList<User> list = new ArrayList<User>();
		
		
		public SearchListAdapter(ArrayList<User> l)
		{
			list = l;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if(convertView == null)
			{
				convertView = LayoutInflater.from(SearchResultUserActivtiy.this).inflate(R.layout.search_result_listitem, null);
			}
			
			TextView name = (TextView)convertView.findViewById(R.id.search_name);
			TextView pcCount =  (TextView)convertView.findViewById(R.id.search_count);
			name.setText(list.get(position).Nickname);
			
			String formatCount = SearchResultUserActivtiy.this.getResources().getString(R.string.search_result_user_count);
			String finalString = String.format(formatCount, list.get(position).PublishCount);
			pcCount.setText(finalString);
			
			ImageView icon = (ImageView)convertView.findViewById(R.id.icon);
			if (list.get(position).HasHeadImg)
	            DrawableManager.getInstance().fetchDrawableOnThread(list.get(position).HeadImgUrl, icon, false);
			return convertView;
		}
		
	}
}
